package com.bringspring.system.base.controller;

import com.alibaba.fastjson.JSONObject;
import com.bringspring.common.base.ActionResult;
import com.bringspring.common.base.ActionResultCode;
import com.bringspring.common.base.NoDataSourceBind;
import com.bringspring.common.config.ConfigValueUtil;
import com.bringspring.common.database.data.DataSourceContextHolder;
import com.bringspring.common.util.JsonUtil;
import com.bringspring.common.util.StringUtils;
import com.bringspring.common.util.UserProvider;
import com.bringspring.common.util.wxutil.HttpUtil;
import com.bringspring.system.base.service.DataInterfaceService;
import com.bringspring.system.base.util.Props;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * 数据接口访问控制器
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2021/3/12 15:31
 */
@Api(tags = "访问数据接口", value = "DataInterfaceRest")
@RestController
@RequestMapping(value = "/api/service")
public class DataInterfaceRestController {
    @Autowired
    private DataInterfaceService dataInterfaceService;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private Props props;

    /**
     * 访问接口
     *
     * @param code 编码
     * @return
     */
    @ApiOperation("访问接口")
    @PostMapping("/{code}")
    @NoDataSourceBind
    public ActionResult getByCode(@PathVariable("code") String code, String tenantId, @RequestBody Map<String,String> map) {
        String name = null;
        if (Boolean.parseBoolean(configValueUtil.getMultiTenancy())) {
            // 判断是不是从外面直接请求
            if (StringUtils.isNotEmpty(tenantId)) {
                //切换成租户库
                JSONObject object = HttpUtil.httpRequest(props.getPortUrl() + tenantId, "GET", null);
                if (object == null || StringUtils.isEmpty(object.getString("data"))) {
                    return ActionResult.fail(ActionResultCode.SessionOverdue.getMessage());
                }
                Map<String, Object> resulList = JsonUtil.stringToMap(object.getString("data"));
                name = resulList.get("java") != null ? String.valueOf(resulList.get("java")) : String.valueOf(resulList.get("dbName"));
                DataSourceContextHolder.setDatasource(tenantId, name);
            } else {
                if (Objects.isNull(userProvider.get())) {
                    return ActionResult.fail(ActionResultCode.SessionOverdue.getMessage());
                }
                DataSourceContextHolder.setDatasource(userProvider.get().getTenantId(), userProvider.get().getTenantDbConnectionString());
            }
        }

        ActionResult actionResult = dataInterfaceService.getApiByCode(code, name, map);
        if (actionResult.getCode() == 200) {
            actionResult.setMsg("接口请求成功");
        }
        return actionResult;
    }
    /**
     * 访问接口
     *
     * @param code 接口code
     * @return
     */
    @ApiOperation("访问接口")
    @GetMapping("/{code}")
    @NoDataSourceBind
    public ActionResult getByCode(@PathVariable("code") String code, String tenantId, HttpServletRequest request) {
        String name = null;
        if (Boolean.parseBoolean(configValueUtil.getMultiTenancy())) {
            // 判断是不是从外面直接请求
            if (StringUtils.isNotEmpty(tenantId)) {
                //切换成租户库
                JSONObject object = HttpUtil.httpRequest(props.getPortUrl() + tenantId, "GET", null);
                if (object == null || StringUtils.isEmpty(object.getString("data"))) {
                    return ActionResult.fail(ActionResultCode.SessionOverdue.getMessage());
                }
                Map<String, Object> resulList = JsonUtil.stringToMap(object.getString("data"));
                name = resulList.get("java") != null ? String.valueOf(resulList.get("java")) : String.valueOf(resulList.get("dbName"));
                DataSourceContextHolder.setDatasource(tenantId, name);
            } else {
                if (Objects.isNull(userProvider.get())) {
                    return ActionResult.fail(ActionResultCode.SessionOverdue.getMessage());
                }
                DataSourceContextHolder.setDatasource(userProvider.get().getTenantId(), userProvider.get().getTenantDbConnectionString());
            }
        }
        // 获取参数映射
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, String> map = new HashMap<>();
        if (!parameterMap.isEmpty()) {
            // 遍历参数映射并处理参数
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                String paramName = entry.getKey();
                String[] paramValues = entry.getValue();
                // 处理每个参数的值
                map.put(paramName, paramValues[0]);
                System.out.println(paramName + paramValues[0]);
            }
        }

        ActionResult actionResult = dataInterfaceService.getApiByCode(code, name, map);
        if (actionResult.getCode() == 200) {
            actionResult.setMsg("接口请求成功");
        }
        return actionResult;
    }

}
